package org.drushpal.service.connecter
{
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	
	import org.drushpal.service.commands.DrushCommandEvent;
	import org.drushpal.model.vo.Connection;

	public class Connecter 
	{
		[Bindable]
		protected var _process:NativeProcess;
		protected var _completeEvent:String; 
		protected var _errorCallback:Function;
		protected var _completeCallback:Function;
		protected var _startupInfo:NativeProcessStartupInfo;
		protected var _queue:ArrayCollection = new ArrayCollection(); //queue of commands being executed
		protected var _busy:Boolean = false;
		[Bindable]
		public var name:String;
		public var output:String;
		[Bindable]
		public var error:String;
		public var uuid:String;
		public var dispatcher:IEventDispatcher;
		
		public function Connecter(onError:Function,onComplete:Function,disp:IEventDispatcher)
		{
			_errorCallback = onError;
			_completeCallback = onComplete;
			dispatcher = disp;
			name="";
			output="";
			error="";
		}
		
		
		
		public function get process():NativeProcess{
			return _process;
		}
		public function set process(value:NativeProcess):void{
			_process=value;
		}		
		
		public function connect(connection:Connection):void{
			
		}
		protected function start():void{
			if(_queue.length){
				next();
			}
		}
		protected function next():void{
			output="";
			_busy=true;
			var command:Object = _queue.getItemAt(0);
			execute(command.cmd,command.onComplete);
		}
		protected function complete():void{
			var i:int = output.indexOf(uuid);
			if(i>0) output=output.substring(0,i); //remove the after and including the uuid;
			dispatcher.dispatchEvent(new DrushCommandEvent(_completeEvent,false,false,output));
			_completeCallback.call(null,output);
			_queue.removeItemAt(0);
			if(_queue.length){
				next();
			}else{	//at the end of the queue
				_busy=false;
			}
		}
		public function addCommand(cmd:String,onComplete:String):void{
			_queue.addItem({cmd:cmd,onComplete:onComplete});
			if(!_busy) next();
			
		}
		
		protected function execute(cmd:String,onComplete:String):void{
			
		}
		
	}
}